// 引入user中的接口函数
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes, anyRoutes } from '@/router'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

// state初始值
const getDefaultState = () => {
  return {
    // token
    token: getToken(),
    // 用户名
    name: '',
    // 用户头像
    avatar: '',
    // 角色列表
    roles: [],
    // 路由列表
    routes: [],
    // 拥有的按钮列表
    buttons: [],
    // 最终要显示的异步路由
    resultAsyncRoutes: [],
    // 最终的路由
    resultRoutes: [],
    // 判断是否有动态添加路由的判断
    isAddRoute: false
  }
}
const state = getDefaultState()

const mutations = {
  // 将仓库重新赋值为初值
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    // 解构赋值
    const { name, avatar, roles, routes, buttons } = userInfo
    state.name = name
    state.avatar = avatar
    state.roles = roles
    state.routes = routes
    state.buttons = buttons
  },
  SER_RESULRROUTES(state, resultAsyncRoutes) {
    // 将最终显示的异步路保存到仓库中
    state.resultAsyncRoutes = resultAsyncRoutes
    // 将最终显示的全部路由保存到仓库中
    state.resultRoutes = constantRoutes.concat(resultAsyncRoutes, anyRoutes)
    // 添加路由
    router.addRoutes(state.resultRoutes)
    state.isAddRoute = true
  }
}

const actions = {
  // 登录的业务
  async login({ commit }, userInfo) {
    // 解构出用户名跟密码
    const { username, password } = userInfo
    const result = await login({ username: username.trim(), password: password })
    if (result.code === 20000) {   
      commit('SET_TOKEN', result.data.token)
      // Cookie存储token
      setToken(result.data.token)
      return 'ok'
    }
    return Promise.reject(new Error('登录失败'))
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        // 保存用户数据
        commit('SET_USERINFO', data)
        // 保存路由数据
        commit('SER_RESULRROUTES', computAsyncRoutes(cloneDeep(asyncRoutes), data.routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录业务
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() //清空token
        resetRouter()
        // 将仓库赋为初值
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
}

// 计算出异步路由中哪些路由在routes中
const computAsyncRoutes = (asyncRoutes, routes) => {
  return asyncRoutes.filter(item => {
    if (routes.indexOf(item.name) !== -1) {
      // 别漏了子路由
      if (item.children && item.children.length) {
        item.children = computAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}

